//
//  WaterFlowLayout.m
//  DebugDemo
//
//  Created by XFB on 2019/6/29.
//  Copyright © 2019 ZhouCheng. All rights reserved.
//

#import "WaterFlowLayout.h"

@interface WaterFlowLayout ()

/**  记录每一列最大Y值  */
@property (nonatomic, strong) NSMutableDictionary *columnMaxYDict;
/**  存放item的位置信息  */
@property (nonatomic, strong) NSMutableArray *attributeArray;

@end

@implementation WaterFlowLayout

#pragma mark --- 构造方法
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.columnCount = 2;
    }
    return self;
}

- (instancetype)initWithColumnCount:(NSInteger)columnCount
{
    self = [super init];
    if (self) {
        self.columnCount = columnCount;
    }
    return self;
}

+ (instancetype)waterFlowLayoutWithColumnCount:(NSInteger)columnCount
{
    return [[self alloc] initWithColumnCount:columnCount];
}

- (void)setColumnSpacing:(NSInteger)columnSpacing
              rowSpacing:(NSInteger)rowSpacing
            sectionInset:(UIEdgeInsets)sectionInset
{
    self.columnSpacing = columnSpacing;
    self.rowSpacing = rowSpacing;
    self.sectionInset = sectionInset;
}

#pragma mark --- 布局方法
- (void)prepareLayout
{
    [super prepareLayout];
    
    for (NSInteger i = 0; i < self.columnCount; i ++) {
        [self.columnMaxYDict setObject:@(self.sectionInset.top) forKey:@(i)];
    }
    
    NSInteger itemCount = [self.collectionView numberOfItemsInSection:0];
    /// 移除所有的 item信息
    [self.attributeArray removeAllObjects];

    /// 得到每个item的属性进行存储
    for (NSInteger i = 0; i < itemCount; i ++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
        [self.attributeArray addObject:attributes];
    }
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    /// 通过indexPath 创建一个item属性 attributes
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    /// 两侧内边距
    CGFloat sectionInsetLeftRight = self.sectionInset.left + self.sectionInset.right;
    /// 总的item之间的间距
    CGFloat totalLineSpacing = (self.columnCount-1) * self.columnSpacing;
    /// 计算每个item宽度
    CGFloat itemWidth = (ScreenW - sectionInsetLeftRight - totalLineSpacing) / self.columnCount;
    /// 计算每个item高度
    CGFloat itemHeight = 0;
    if ([self.delegate respondsToSelector:@selector(waterFlowLayout:itemWidth:indexPath:)]) {
        itemHeight = [self.delegate waterFlowLayout:self itemWidth:itemWidth indexPath:indexPath];
    }
    
    /// 找出最短的那一列
    __block NSNumber *minColumnIndex = @(0);
    [self.columnMaxYDict enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, NSNumber *_Nonnull obj, BOOL * _Nonnull stop) {
        if ([self.columnMaxYDict[minColumnIndex] floatValue] > [obj floatValue]) {
            minColumnIndex = key;
        }
    }];
    
    /// 根据最短列计算 item的 x值
    NSInteger minColumnIndexInt = [minColumnIndex integerValue];
    
    CGFloat itemX = self.sectionInset.left + (self.columnSpacing + itemWidth) * minColumnIndexInt;
    CGFloat itemY = [self.columnMaxYDict[minColumnIndex] floatValue] + self.rowSpacing;

    attributes.frame = CGRectMake(itemX, itemY, itemWidth, itemHeight);
    /// 更新字典中的最大Y值
    self.columnMaxYDict[minColumnIndex] = @(CGRectGetMaxY(attributes.frame));
    return attributes;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return self.attributeArray;
}

- (CGSize)collectionViewContentSize
{
    __block NSNumber *coloumnMaxIndex = @(0);
    /// 遍历字典找出最长的那一列
    [self.columnMaxYDict enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
        if ([self.columnMaxYDict[coloumnMaxIndex] floatValue]  < [obj floatValue]) {
            coloumnMaxIndex = key;
        }
    }];
    /// collectionView 的 contentSize.height 等于最长列的最大 Y 值 + 下边距
    return CGSizeMake(0, [self.columnMaxYDict[coloumnMaxIndex] floatValue] + self.sectionInset.bottom);
}

#pragma mark -- <Lazy loading>
- (NSMutableDictionary *)columnMaxYDict
{
    if (!_columnMaxYDict) {
        _columnMaxYDict = [[NSMutableDictionary alloc] init];
    }
    return _columnMaxYDict;
}

- (NSMutableArray *)attributeArray
{
    if (!_attributeArray) {
        _attributeArray = @[].mutableCopy;
    }
    return _attributeArray;
}

@end
